<template>
  <div class="employee-container">
    <!-- 搜索条件卡片 -->
    <a-card class="search-card" :bordered="false">
      <a-form :model="searchForm" class="search-form">
        <div class="search-row">
          <a-form-item label="员工账号" class="search-item">
            <a-input
              v-model:value="searchForm.account"
              placeholder="请输入员工账号"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="员工姓名" class="search-item">
            <a-input
              v-model:value="searchForm.name"
              placeholder="请输入员工姓名"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="" class="search-item search-buttons">
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon><search-outlined /></template>
                查询
              </a-button>
              <a-button @click="resetSearch">
                <template #icon><reload-outlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </div>
      </a-form>
    </a-card>

    <!-- 员工列表卡片 -->
    <a-card class="employee-card" :bordered="false">
      <template #title>
        <div class="card-header">
          <a-button v-permission="'system:employee:create'" type="primary" @click="handleAdd" class="add-button">
            <template #icon><plus-outlined /></template>
            添加员工
          </a-button>
        </div>
      </template>

      <a-table
        :dataSource="tableData"
        :columns="columns"
        :loading="loading"
        :pagination="false"
        rowKey="id"
        bordered
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'gender'">
            <a-tag :color="GENDER_CONFIG[record.gender]?.color">
              {{ GENDER_CONFIG[record.gender]?.label }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="EMPLOYEE_STATUS[record.status]?.color">
              {{ EMPLOYEE_STATUS[record.status]?.label }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'phone'">
            <div
              style="
                display: flex;
                align-items: center;
                justify-content: center;
              "
            >
              <span style="color: #1890ff">{{ record.phone }}</span>
              <a-button
                v-permission="'system:employee:view:phone'"
                type="link"
                style="padding: 0 0 0 5px"
                @click.stop="handleViewPhone(record)"
              >
                <template #icon><eye-outlined /></template>
              </a-button>
            </div>
          </template>

          <template v-else-if="column.key === 'action'">
            <div class="action-btns">
              <a-button
                v-if="record.status === STATUS_KEYS.EMPLOYEE.INIT"
                v-permission="'system:employee:update'"
                type="link"
                @click="handleEdit(record)"
                >编辑</a-button
              >
              <a-button
                v-if="record.status !== STATUS_KEYS.EMPLOYEE.ENABLE"
                v-permission="'system:employee:enable'"
                type="link"
                @click="handleEnable(record)"
                >启用</a-button
              >
              <a-button
                v-if="record.status === STATUS_KEYS.EMPLOYEE.ENABLE"
                v-permission="'system:employee:disable'"
                type="link"
                danger
                @click="handleDisable(record)"
                >禁用</a-button
              >
              <a-button
                v-if="record.status === STATUS_KEYS.EMPLOYEE.INIT"
                v-permission="'system:employee:delete'"
                type="link"
                danger
                @click="handleDelete(record)"
                >删除</a-button
              >
            </div>
          </template>
        </template>
      </a-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <a-pagination
          v-model:current="currentPage"
          v-model:pageSize="pageSize"
          :total="total"
          :pageSizeOptions="['10', '20', '50', '100']"
          showSizeChanger
          showQuickJumper
          :showTotal="(total) => `共 ${total} 条`"
          @change="handlePageChange"
          @showSizeChange="handleSizeChange"
          :locale="{ items_per_page: '条/页', jump_to: '跳至', page: '页' }"
        />
      </div>
    </a-card>

    <!-- 创建员工组件 -->
    <create-employee
      v-model:visible="createVisible"
      @success="fetchEmployees"
    />

    <!-- 编辑员工组件 -->
    <edit-employee
      v-model:visible="editVisible"
      :employee-data="currentEmployee"
      @success="fetchEmployees"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, h } from "vue";
import { message, Modal } from "ant-design-vue";
import {
  SearchOutlined,
  ReloadOutlined,
  PlusOutlined,
  EyeOutlined,
  CopyOutlined,
} from "@ant-design/icons-vue";
import {
  getEmployeeList,
  deleteEmployee,
  enableEmployee,
  disableEmployee,
  getDecryptedPhone,
} from "@/api/employee";
import CreateEmployee from "./components/CreateEmployee.vue";
import EditEmployee from "./components/EditEmployee.vue";
import { EMPLOYEE_STATUS, GENDER_CONFIG, STATUS_KEYS } from "@/constants/constants";

// 表格列定义
const columns = [
  { title: "员工ID", dataIndex: "id", key: "id", width: 80, align: "center" },
  {
    title: "员工账号",
    dataIndex: "account",
    key: "account",
    width: 120,
    align: "center",
  },
  {
    title: "员工姓名",
    dataIndex: "name",
    key: "name",
    width: 120,
    align: "center",
  },
  {
    title: "手机号",
    dataIndex: "phone",
    key: "phone",
    width: 140,
    align: "center",
  },
  {
    title: "邮箱",
    dataIndex: "email",
    key: "email",
    width: 160,
    align: "center",
  },
  {
    title: "性别",
    dataIndex: "gender",
    key: "gender",
    width: 60,
    align: "center",
  },
  {
    title: "状态",
    dataIndex: "status",
    key: "status",
    width: 60,
    align: "center",
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    width: 240,
    align: "center",
  },
  { title: "操作", key: "action", fixed: "right", width: 220, align: "center" },
];

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 搜索表单
const searchForm = reactive({
  name: "",
  account: "",
});

// 对话框控制
const createVisible = ref(false);
const editVisible = ref(false);
const currentEmployee = ref({});

// 页面加载时获取数据
onMounted(() => {
  fetchEmployees();
});

// 获取员工列表
const fetchEmployees = async () => {
  loading.value = true;
  try {
    const res = await getEmployeeList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name,
      account: searchForm.account,
    });
    tableData.value = res.data.items;
    total.value = res.data.totalRow;
  } catch (error) {
    message.error("获取员工列表失败");
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchEmployees();
};

// 重置搜索
const resetSearch = () => {
  searchForm.name = "";
  searchForm.account = "";
  handleSearch();
};

// 页码变化
const handlePageChange = (page) => {
  // 由于使用了v-model:current绑定，这里不需要手动设置currentPage.value
  fetchEmployees();
};

// 页大小变化
const handleSizeChange = (current, size) => {
  // 由于使用了v-model:pageSize绑定，这里不需要手动设置pageSize.value
  // 但需要重置到第一页
  currentPage.value = 1;
  fetchEmployees();
};

// 添加员工
const handleAdd = () => {
  createVisible.value = true;
};

// 编辑员工
const handleEdit = (record) => {
  currentEmployee.value = { ...record };
  editVisible.value = true;
};

// 启用员工
const handleEnable = (record) => {
  Modal.confirm({
    title: "确认启用",
    content: `确定要启用员工【${record.name}】 吗？`,
    okText: "确定",
    cancelText: "取消",
    async onOk() {
      try {
        await enableEmployee(record.id);
        message.success("启用成功");
        fetchEmployees();
      } catch (error) {
        message.error("启用失败");
      }
    },
  });
};

// 禁用员工
const handleDisable = (record) => {
  Modal.confirm({
    title: "确认禁用",
    content: `确定要禁用员工 ${record.name} 吗？`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        await disableEmployee(record.id);
        message.success("禁用成功");
        fetchEmployees();
      } catch (error) {
        message.error("禁用失败");
      }
    },
  });
};

// 删除员工
const handleDelete = (record) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除员工 ${record.name} 吗？`,
    okText: "确定",
    okType: "danger",
    cancelText: "取消",
    async onOk() {
      try {
        await deleteEmployee(record.id);
        message.success("删除成功");
        fetchEmployees();
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};

// 复制文本到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard
    .writeText(text)
    .then(() => {
      message.success("复制成功");
    })
    .catch(() => {
      message.error("复制失败");
    });
};

// 查看解密的手机号
const handleViewPhone = async (record) => {
  try {
    const res = await getDecryptedPhone(record.id);
    if (res.data) {
      const phoneNumber = res.data;
      Modal.info({
        title: "解密的手机号",
        icon: h(EyeOutlined, { style: { color: "#1890ff" } }),
        content: h("div", { class: "phone-modal-content" }, [
          h("p", { class: "employee-name" }, `${record.name}`),
          h("div", { class: "phone-container" }, [
            h("span", { class: "phone-number" }, phoneNumber),
            h(
              "a-button",
              {
                type: "link",
                class: "copy-button",
                onClick: () => copyToClipboard(phoneNumber),
              },
              [h(CopyOutlined)]
            ),
          ]),
        ]),
        okText: "确定",
        class: "custom-phone-modal",
      });
    }
  } catch (error) {
    message.error("获取解密手机号失败");
  }
};
</script>

<style lang="scss" scoped>
.employee-container {
  padding: 16px;

  .search-card {
    margin-bottom: 16px;

    :deep(.ant-card-body) {
      padding: 16px;
    }

    .search-form {
      .search-row {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;

        .search-item {
          flex: 0 0 calc(33.333% - 11px);
          margin-bottom: 0;

          :deep(.ant-form-item-label) {
            width: 80px;
            text-align: right;
          }

          :deep(.ant-form-item-control) {
            flex: 1;
          }
        }
      }

      .search-buttons {
        :deep(.ant-form-item-label) {
          display: none;
        }

        :deep(.ant-space) {
          display: flex;
          justify-content: flex-start;
        }
      }
    }
  }

  .employee-card {
    :deep(.ant-card-head) {
      min-height: 48px;
      padding: 0 16px;

      .ant-card-head-title {
        padding: 12px 0;
      }
    }

    :deep(.ant-card-body) {
      padding: 16px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }

    .action-btns {
      display: flex;
      gap: 4px;
      justify-content: center;
    }

    :deep(.ant-table-thead > tr > th) {
      text-align: center;
    }
  }

  .pagination-container {
    margin-top: 16px;
    text-align: right;
  }
}

/* 自定义手机号弹窗样式 */
:deep(.custom-phone-modal) {
  .ant-modal-confirm-content {
    margin-top: 16px;
  }

  .phone-modal-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 16px;

    .employee-name {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 12px;
      color: #333;
    }

    .phone-container {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #f5f5f5;
      padding: 8px 16px;
      border-radius: 4px;

      .phone-number {
        font-size: 18px;
        color: #1890ff;
        font-weight: 500;
        margin-right: 8px;
      }

      .copy-button {
        padding: 0;
        height: auto;

        &:hover {
          color: #40a9ff;
        }
      }
    }
  }
}
</style>
